package com.yq.cns.adapter.newsitem

import android.os.Parcelable
import androidx.recyclerview.widget.LinearLayoutManager2
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.fmt.mvi.learn.gobal.log
import com.yq.cns.R
import com.yq.cns.entity.ListItemType
import com.yq.cns.entity.NewsListEntity

/**
 * 横向多联发
 */
class DlfTransverseItemProvider : BaseItemProvider<NewsListEntity>() {
    override val itemViewType: Int
        get() = ListItemType.TYPE_DLF_TRANSVERSE
    override val layoutId: Int
        get() = R.layout.news_item_dlf_transverse

    companion object {
        val map = HashMap<Int, Parcelable>()
    }

    override fun convert(helper: BaseViewHolder, item: NewsListEntity) {
        helper.setText(R.id.tvTitle, item.dlfTitle)
        val mAdapter = SubRvAdapter()
        val mRv = helper.getView<RecyclerView>(R.id.mRv)
        mRv.layoutManager = LinearLayoutManager2(
            context,
            RecyclerView.HORIZONTAL,
            false
        )
        mRv.adapter = mAdapter
        mAdapter.addData(item.dlfList)

    }

    override fun onViewAttachedToWindow(holder: BaseViewHolder) {
        super.onViewAttachedToWindow(holder)
        "onViewAttachedToWindow".log()
        val parcelable = map.get(holder.absoluteAdapterPosition)
        val mRv = holder.getView<RecyclerView>(R.id.mRv)

        if (parcelable != null) {
            mRv.layoutManager?.onRestoreInstanceState(parcelable)
        }


    }

    override fun onViewDetachedFromWindow(holder: BaseViewHolder) {
        super.onViewDetachedFromWindow(holder)
        "onViewDetachedFromWindow".log()
        val mRv = holder.getView<RecyclerView>(R.id.mRv)
        val parcelable = mRv.layoutManager?.onSaveInstanceState()
        parcelable?.let {
            map.put(holder.absoluteAdapterPosition, it)
        }
    }


    class SubRvAdapter :
        BaseQuickAdapter<NewsListEntity, BaseViewHolder>(R.layout.news_item_dlf_transverse_item) {
        override fun convert(holder: BaseViewHolder, item: NewsListEntity) {
            holder.setText(R.id.headlines_view_title_tv, item.title)
            Glide.with(context).load(item.picture).into(holder.getView(R.id.iv_viewpager_head))
        }

    }
}